#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include "terrain.h"



int Get_Dimx (const _terrain* Terrain){
assert(Terrain != NULL);
return Terrain->Dimx;
}

int Get_Dimy(const _terrain* Terrain){
assert(Terrain != NULL);
return Terrain->Dimy;
}


int Get_Case(const _terrain* Terrain,const int x, const int y){
assert(Terrain != NULL);
return Terrain->Cases[x][y];
}

int Get_Nom(const _terrain* Terrain){
assert(Terrain != NULL);
return Terrain->Nom;
}





void Set_Dimx (_terrain* Terrain,const int Dimx){
assert(Terrain!= NULL);
Terrain->Dimx = Dimx;
assert(Terrain->Dimx == Dimx);
}

void Set_Dimy(_terrain* Terrain,const int Dimy){
assert(Terrain!= NULL);
Terrain->Dimy = Dimy;
assert(Terrain->Dimy == Dimy);
}

void Set_Case(_terrain* Terrain,const int Case, const int x, const int y){
assert(Terrain!= NULL);
Terrain->Cases[x][y] = Case;
assert(Terrain->Cases[x][y] == Case);
}

void Set_Nom(_terrain* Terrain,const int Nom){
assert(Terrain!= NULL);
Terrain->Nom = Nom;
assert(Terrain->Nom == Nom);
}

_terrain* Init_Terrain()
{	
	int i,j,Temp1, Temp2;

	_terrain* Terrain;
	Terrain =(_terrain*) malloc ( sizeof (_terrain) ); // malloc corrigé casté
	
/*Allocation du tableau de cases ...*/
	Terrain->Cases= (int**) malloc ( sizeof(int*) * DIMX);
	for ( i=0;i<DIMX;i++)
		Terrain->Cases[i]= (int*) malloc (sizeof(int) * DIMY); 





	Terrain->Dimx = DIMX;
	Terrain->Dimy = DIMY;

	Temp1 = ((Terrain->Dimx)/2)-4; // =7
	Temp2 = ((Terrain->Dimx)/2)+4; // =15

	for(j=0; j < 4 ;j++) 
	{
		for(i=Temp1; i < Temp2 ;i++)
		{
			Terrain->Cases[i][j] = -1;
		
		}

	}


	for(j=18; j < 22 ;j++)
	{
		for(i=Temp1; i < Temp2 ;i++)
		{
			Terrain->Cases[i][j] = -2;

		}
	}

	Temp1 = ((Terrain->Dimy)/2)-4; //7
	Temp2 = ((Terrain->Dimy)/2)+4; //15	

	for(j=Temp1; j < Temp2 ;j++)
	{
		for(i=0; i < 4 ;i++)
		{
			Terrain->Cases[i][j] = -3;

		}
	}

	for(j=Temp1; j < Temp2 ;j++)
	{
		for(i=18; i < 22 ;i++)
		{
			Terrain->Cases[i][j] = -4;

		}
	}

	return Terrain;
}

void Libere_Terrain( _terrain* Terrain)
{
int i;
printf("debug0");
for(i=0; i<DIMX; i++){
	free(Terrain->Cases[i]);
	printf("%d \n",i);
}
printf("debug1");
free(Terrain->Cases);
printf("debug2");
free(Terrain);
printf("debug3");
}



void Set_Terrain(_terrain* Terrain, const int Carte){ // compile, à tester

FILE* file;
char c = 'a';
int i =0;
int j =0;

switch (Carte){
case 1:
	file = fopen("Prairie.txt","r");
	break;
case 2:
	file = fopen("Foret.txt","r");
	break;	
case 3:
	file = fopen("Cuvette.txt","r");
	break;
}
;
while ( i <= DIMX && j <= DIMY ){
 
	fscanf(file,"%c",&c);

	if ( c == '\n'){
		i =0;
		j ++;
	}
	else {
		Terrain->Cases[i][j] = c-'0';
		i++;	
	}	

}

}




void Enleve_Zone_Placement ( _terrain* Terrain){
int i,j;
for (i = 0; i<DIMY;i++){
	for ( j = 0; j<DIMX; i++){
		if ( Terrain->Cases[j][i] < 0)
			Terrain->Cases[j][i] = 0;
	}
}


}
